import { createElement } from 'react';
import dynamic from 'dva/dynamic';
import pathToRegexp from 'path-to-regexp';
import { getMenuData } from './menu';
import product from '../models/product';

let routerDataCache;

const modelNotExisted = (app, model) =>
  // eslint-disable-next-line
  !app._models.some(({ namespace }) => {
    return namespace === model.substring(model.lastIndexOf('/') + 1);
  });

// wrapper of dynamic
const dynamicWrapper = (app, models, component) => {
  // () => require('module')
  // transformed by babel-plugin-dynamic-import-node-sync
  if (component.toString().indexOf('.then(') < 0) {
    models.forEach(model => {
      if (modelNotExisted(app, model)) {
        // eslint-disable-next-line
        app.model(require(`../models/${model}`).default);
      }
    });
    return props => {
      if (!routerDataCache) {
        routerDataCache = getRouterData(app);
      }
      return createElement(component().default, {
        ...props,
        routerData: routerDataCache,
      });
    };
  }
  // () => import('module')
  return dynamic({
    app,
    models: () =>
      models.filter(model => modelNotExisted(app, model)).map(m => import(`../models/${m}.js`)),
    // add routerData prop
    component: () => {
      if (!routerDataCache) {
        routerDataCache = getRouterData(app);
      }
      return component().then(raw => {
        const Component = raw.default || raw;
        return props =>
          createElement(Component, {
            ...props,
            routerData: routerDataCache,
          });
      });
    },
  });
};

function getFlatMenuData(menus) {
  let keys = {};
  menus.forEach(item => {
    if (item.children) {
      keys[item.path] = { ...item };
      keys = { ...keys, ...getFlatMenuData(item.children) };
    } else {
      keys[item.path] = { ...item };
    }
  });
  return keys;
}

export const getRouterData = app => {
  const routerConfig = {
    '/': {
      component: dynamicWrapper(app, ['user', 'login'], () => import('../layouts/BasicLayout')),
    },
    '/dashboard/analysis': {
      component: dynamicWrapper(app, ['chart'], () => import('../routes/Dashboard/Analysis')),
    },
    '/dashboard/monitor': {
      component: dynamicWrapper(app, ['monitor'], () => import('../routes/Dashboard/Monitor')),
    },
    '/dashboard/workplace': {
      component: dynamicWrapper(app, ['project', 'activities', 'chart'], () =>
        import('../routes/Dashboard/Workplace')
      ),
      // hideInBreadcrumb: true,
      // name: '工作台',
      // authority: 'admin',
    },

    '/risk/preCheck': {
      component: dynamicWrapper(app, ['risk'], () =>
        import('../routes/Risk/PreCheck/PreCheckDetail')
      ),
    },

    '/risk/review': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Review/Review')),
    },

    '/risk/reviewList': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Review/ReviewList')),
    },

    '/risk/reviewDetail': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Review/ReviewDetail')),
    },

    //-----------------------首页
    '/home/home-page': {
      component: dynamicWrapper(app, ['home'], () => import('../routes/Home/HomePage')),
    },

    //---------------------产品管理
    '/product/product-catalog': {
      component: dynamicWrapper(app, ['product', 'channel'], () => import('../routes/Product/ProductCatalog')),
    },
    '/product/product-details': {
      component: dynamicWrapper(app, ['product', 'channel'], () => import('../routes/Product/ProductDetails')),
    },
    '/product/product-add': {
      component: dynamicWrapper(app, ['product'], () => import('../routes/Product/ProductAdd')),
    },
    '/product/product-list': {
      component: dynamicWrapper(app, ['product'], () => import('../routes/Product/ProductList')),
    },
    '/product/product-acquisition': {
      component: dynamicWrapper(app, ['product'], () =>
        import('../routes/Product/ProductAcquisition')
      ),
    },
    //---------------------渠道管理

    '/channel/channel-form': {
      component: dynamicWrapper(app, ['channel'], () => import('../routes/Channel/ChannelForm')),
    },
    '/channel/channel-form/customer': {
      component: dynamicWrapper(app, ['channel', 'system'], () =>
        import('../routes/Channel/ChannelForm/Step1')
      ),
    },
    // '/channel/channel-form/business': {
    //   component: dynamicWrapper(app, ['channel'], () => import('../routes/Channel/ChannelForm/Step2')),
    // },
    '/channel/channel-form/credits': {
      component: dynamicWrapper(app, ['channel'], () =>
        import('../routes/Channel/ChannelForm/Step3')
      ),
    },
    '/channel/channel-form/pay': {
      component: dynamicWrapper(app, ['channel'], () =>
        import('../routes/Channel/ChannelForm/Step4')
      ),
    },
    //经销商列表
    '/channel/channel-maintenance': {
      component: dynamicWrapper(app, ['channel'], () =>
        import('../routes/Channel/ChannelMaintenance')
      ),
    },
    //经销商审核
    '/channel/dealer-audit': {
      component: dynamicWrapper(app, ['channel'], () => import('../routes/Channel/DealerAudit')),
    },
    //经销商详情和审核详情
    '/channel/channel-details': {
      component: dynamicWrapper(app, ['channel'], () => import('../routes/Channel/ChannelDetails')),
    },
    //经销商详情和审核详情
    '/channel/channel-risk-management': {
      component: dynamicWrapper(app, ['channel'], () =>
        import('../routes/Channel/ChannelRiskManagement')
      ),
    },
    //渠道的渠道信息修改
    '/channel/channel-details-updata': {
      component: dynamicWrapper(app, ['channel', 'system'], () =>
        import('../routes/Channel/ChannelDetailsUpdata')
      ),
    },
    //渠道的渠道详情的产品信息修改
    // '/channel/channel-product-details-updata': {
    //   component: dynamicWrapper(app, ['channel'], () => import('../routes/Channel/ChannelProductDetailsUpdata')),
    // },
    //客户管理
    '/customer/customer-management': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/CustomerManagement')
      ),
    },
    '/customer/customer-details': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/CustomerDetails')
      ),
    },
    '/customer-details': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/CustomerDetails')
      ),
    },

    '/customer/customer-sales-tracking': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/CustomerSalesTracking')
      ),
    },
    //客户分派
    '/customer/platform-assignment': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/PlatformAssignment')
      ),
    },
    //客户分派-分派功能
    '/customer/choice-org': {
      component: dynamicWrapper(app, ['customer'], () => import('../routes/Customer/ChoiceOrg')),
    },
    //客户指派
    '/customer/org-assignment': {
      component: dynamicWrapper(app, ['customer'], () =>
        import('../routes/Customer/OrgAssignment')
      ),
    },

    /*
     --------业务管理--------
     */
    //业务列表
    '/apply/applyIndex': {
      component: dynamicWrapper(app, ['apply', 'home'], () =>
        import('../routes/Apply/ApplyIndex/ApplyIndex')
      ),
    },
    //业务管理 - 业务申请列表
    '/apply/createApplyList': {
      component: dynamicWrapper(app, ['apply', 'risk'], () =>
        import('../routes/Apply/Create/CreateApplyList')
      ),
    },
    //业务管理 - 业务申请
    '/apply/createApply': {
      component: dynamicWrapper(app, ['apply'], () => import('../routes/Apply/Create/CreateApply')),
    },
    //业务管理 - 业务受理
    '/apply/operateList': {
      component: dynamicWrapper(app, ['apply', 'risk'], () =>
        import('../routes/Apply/Operate/OperateList')
      ),
    },
    '/apply/operateDetail': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/Operate/OperateDetail')
      ),
    },

    //业务管理 - 业务详情
    '/apply/fillApply': {
      component: dynamicWrapper(app, ['apply'], () => import('../routes/Apply/Fill/FillApply')),
    },
    //业务管理 - 业务详情
    '/apply/fillList': {
      component: dynamicWrapper(app, ['apply'], () => import('../routes/Apply/Fill/FillList')),
    },
    //业务管理 - 审核驳回
    '/apply/reviewRejectList': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/Review/ReviewRejectList')
      ),
    },
    //业务管理 - 申请资料
    '/apply/businessSupplementList': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/Supplement/BusinessSupplementList')
      ),
    },
    //业务管理 - 签约管理列表
    '/apply/signContractList': {
      component: dynamicWrapper(app, ['apply', 'risk'], () =>
        import('../routes/Apply/Contract/SignContractList')
      ),
    },
    //业务管理 - 签约管理 详情
    '/apply/signContractDetail': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/Contract/SignContractDetail')
      ),
    },
    //业务管理 - 提车服务列表
    '/apply/pickCarEditorList': {
      component: dynamicWrapper(app, ['apply', 'risk'], () =>
        import('../routes/Apply/PickCar/PickCarEditorList')
      ),
    },
    //业务管理 - 提车服务详情
    '/apply/pickCarEditorDetail': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/PickCar/PickCarEditorDetail')
      ),
    },
    //业务管理 - 上报银行
    '/apply/reportBrankList': {
      component: dynamicWrapper(app, ['risk', 'apply'], () =>
        import('../routes/Apply/Report/ReportBrankList')
      ),
    },

    //业务管理 - 预付费明细
    '/apply/prePay': {
      component: dynamicWrapper(app, ['apply', 'risk'], () =>
        import('../routes/Apply/PrePay/PrePayList')
      ),
    },

    //业务管理 - 业务补导入(山东)
    '/apply/businessImport': {
      component: dynamicWrapper(app, ['supplement'], () =>
        import('../routes/Apply/Business/BusinessImport')
      ),
    },

    //业务管理 - 业务补导入详情
    '/apply/businessDetails': {
      component: dynamicWrapper(app, ['supplement', 'risk', 'apply'], () =>
        import('../routes/Apply/Business/BusinessDetails')
      ),
    },

    //风险管理
    '/risk/riskInex': {
      component: dynamicWrapper(app, ['risk', 'apply', 'home'], () =>
        import('../routes/Risk/RiskIndex/RiskIndex')
      ),
    },
    //风险管理 -  初筛
    '/risk/preCheckList': {
      component: dynamicWrapper(app, ['risk'], () =>
        import('../routes/Risk/PreCheck/PreCheckList')
      ),
    },

    '/risk/preCheckDetail': {
      component: dynamicWrapper(app, ['risk'], () =>
        import('../routes/Risk/PreCheck/PreCheckDetail')
      ),
    },

    //风险管理 -  初筛  单独的
    '/risk/alonePreCheckList': {
      component: dynamicWrapper(app, ['risk','apply'], () =>
        import('../routes/Risk/Alone/AlonePreCheckList')
      ),
    },

    '/risk/alonePreCheckDetail': {
      component: dynamicWrapper(app, ['risk','apply'], () =>
        import('../routes/Risk/Alone/AlonePreCheckDetail')
      ),
    },

    //风险管理 -  家访
    '/risk/homeVisitList': {
      component: dynamicWrapper(app, ['risk'], () =>
        import('../routes/Risk/HomeVisit/HomeVisitList')
      ),
    },
    '/risk/homeVisitDetail': {
      component: dynamicWrapper(app, ['risk', 'apply'], () =>
        import('../routes/Risk/HomeVisit/HomeVisitDetail')
      ),
    },

    //风险管理 -  业务审核
    '/risk/checkList': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Check/CheckList')),
    },
    '/risk/checkDetail': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Check/CheckDetail')),
    },

    //风险管理 -  复审
    '/risk/reviewList': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Review/ReviewList')),
    },
    '/risk/reviewDetail': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/Review/ReviewDetail')),
    },

    //风险管理 -  放款
    '/apply/cashOutList': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/CashOut/CashOutList')
      ),
    },
    '/apply/cashOutDetail': {
      component: dynamicWrapper(app, ['apply'], () =>
        import('../routes/Apply/CashOut/CashOutDetail')
      ),
    },

    //风险管理 -  提车
    '/risk/pickCarList': {
      component: dynamicWrapper(app, ['risk'], () => import('../routes/Risk/PickCar/PickCarList')),
    },
    '/risk/pickCarDetail': {
      component: dynamicWrapper(app, ['risk', 'apply'], () =>
        import('../routes/Risk/PickCar/PickCarDetail')
      ),
    },

    //修改密码
    '/system/updata-password': {
      component: dynamicWrapper(app, ['users'], () => import('../routes/System/UpdataPassword')),
    },

    //组织架构维护
    '/system/structure-maintenance': {
      component: dynamicWrapper(app, ['system'], () =>
        import('../routes/System/StructureMaintenance')
      ),
    },

    //添加组织架构
    '/system/system-form': {
      component: dynamicWrapper(app, ['system'], () => import('../routes/System/SystemForm')),
    },

    //员工管理
    '/system/employee-management': {
      component: dynamicWrapper(app, ['system', 'role'], () =>
        import('../routes/System/EmployeeManagement')
      ),
    },

    //角色管理
    '/system/role-management': {
      component: dynamicWrapper(app, ['role'], () => import('../routes/System/RoleManagement')),
    },
    //角色配置
    '/system/role-authorization': {
      component: dynamicWrapper(app, ['role'], () => import('../routes/System/RoleAuthorization')),
    },
    //组织架构的新增和编辑  分步表单
    '/system/system-form/customer': {
      component: dynamicWrapper(app, ['system'], () => import('../routes/System/SystemForm/Step1')),
    },
    '/system/system-form/credits': {
      component: dynamicWrapper(app, ['system', 'product'], () =>
        import('../routes/System/SystemForm/Step3')
      ),
    },
    '/system/system-form/pay': {
      component: dynamicWrapper(app, ['system'], () => import('../routes/System/SystemForm/Step4')),
    },

    '/search/allocation-rules': {
      component: dynamicWrapper(app, ['system'], () => import('../routes/Search/AllocationRules')),
    },
    '/search/task-signed': {
      component: dynamicWrapper(app, ['system'], () => import('../routes/Search/TaskSigned')),
    },
    '/search/task-list': {
      component: dynamicWrapper(app, ['system', 'risk'], () => import('../routes/Search/TaskList')),
    },
    '/search/task-dispatch': {
      component: dynamicWrapper(app, ['system', 'risk'], () => import('../routes/Search/TaskDispatch')),
    },

    //消息列表
    '/system/message-notification': {
      component: dynamicWrapper(app, ['system'], () =>
        import('../routes/System/MessageNotification')
      ),
    },

    '/form/basic-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/BasicForm')),
    },
    '/form/step-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm')),
    },
    '/form/step-form/info': {
      name: '分步表单（填写转账信息）',
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step1')),
    },
    '/form/step-form/confirm': {
      name: '分步表单（确认转账信息）',
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step2')),
    },
    '/form/step-form/result': {
      name: '分步表单（完成）',
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step3')),
    },
    '/form/advanced-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/AdvancedForm')),
    },
    '/list/table-list': {
      component: dynamicWrapper(app, ['rule'], () => import('../routes/List/TableList')),
    },
    '/list/basic-list': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/BasicList')),
    },
    '/list/card-list': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/CardList')),
    },
    '/list/search': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/List')),
    },
    '/list/search/projects': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Projects')),
    },
    '/list/search/applications': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Applications')),
    },
    '/list/search/articles': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Articles')),
    },
    '/profile/basic': {
      component: dynamicWrapper(app, ['profile'], () => import('../routes/Profile/BasicProfile')),
    },
    '/profile/advanced': {
      component: dynamicWrapper(app, ['profile'], () =>
        import('../routes/Profile/AdvancedProfile')
      ),
    },
    '/result/success': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Success')),
    },
    '/result/fail': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Error')),
    },
    '/exception/403': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/403')),
    },
    '/exception/404': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/404')),
    },
    '/exception/500': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/500')),
    },
    '/exception/trigger': {
      component: dynamicWrapper(app, ['error'], () =>
        import('../routes/Exception/triggerException')
      ),
    },
    '/user': {
      component: dynamicWrapper(app, [], () => import('../layouts/UserLayout')),
    },
    '/user/login': {
      component: dynamicWrapper(app, ['login'], () => import('../routes/User/Login')),
    },
    '/user/register': {
      component: dynamicWrapper(app, ['register'], () => import('../routes/User/Register')),
    },
    '/user/register-result': {
      component: dynamicWrapper(app, [], () => import('../routes/User/RegisterResult')),
    },
    // '/user/:id': {
    //   component: dynamicWrapper(app, [], () => import('../routes/User/SomeComponent')),
    // },
  };
  // Get name from ./menu.js or just set it in the router data.
  const menuData = getFlatMenuData(getMenuData());

  // Route configuration data
  // eg. {name,authority ...routerConfig }
  const routerData = {};
  // The route matches the menu
  Object.keys(routerConfig).forEach(path => {
    // Regular match item name
    // eg.  router /user/:id === /user/chen
    const pathRegexp = pathToRegexp(path);
    const menuKey = Object.keys(menuData).find(key => pathRegexp.test(`${key}`));
    let menuItem = {};
    // If menuKey is not empty
    if (menuKey) {
      menuItem = menuData[menuKey];
    }
    let router = routerConfig[path];
    // If you need to configure complex parameter routing,
    // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
    // eg . /list/:type/user/info/:id
    router = {
      ...router,
      name: router.name || menuItem.name,
      authority: router.authority || menuItem.authority,
      hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb,
    };
    routerData[path] = router;
  });
  return routerData;
};
